//
//  TokenMiddleware.swift
//  App
//
//  Created by chenyh on 2018/5/25.
//
import Vapor
import CNIOHTTPParser
final class TokenMiddleware: Middleware {
    
    func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
        //只需要不给auth模块设置中间件就行
        //这里需要过滤掉 登录、注册、忘记密码
        // if !request.http.urlString.contains("auth") {
//            return try next.respond(to: request)
//        }

        print(request)
        //判断地址中是否存在这个Token
        guard let token =   request.http.headers.firstValue(name: HTTPHeaderName.authorization) else {
            return  ErrorModel(status: 10086, message: "登录会话不存在", result: nil).encode(status: HTTPStatus.custom(code: UInt(10086), reasonPhrase: "登录会话不存在"), for: request)
           
        }
        
        let session = try Account.userExist(req: request, token: token).flatMap({ (account) -> EventLoopFuture<Response> in
            guard account != nil else {
                throw Abort(HTTPStatus.custom(code: UInt(10086), reasonPhrase: "登录会话不存在"), reason: "会话已失效,请重新登录!")
            }
            return try next.respond(to: request)
        })
        
        return session
        
//        try? Account.userExist(req: request, token: token).flatMap({ (account) -> EventLoopFuture<Response> in
//            if account == nil {
//                return ErrorModel(status: 10010, message: "登录会话已失效,请重新登录", result: nil).encode(status: .nonAuthoritativeInformation, for: request)
//            }
//
//        })
//        if let digest = try? SHA1.hash(self.id!) {
//            print(digest.hexEncodedString())
//            self.token = digest.hexEncodedString(uppercase: true)
//        }
        //直接匹配 还是 双向验证？ 双向验证能更安全 直接
        //1.通过该token是否能够找到用户信息、可以先从缓存中找：找到和找不到
        //1.1.找不到则代表新登录
        //1.2.找得到则需要进一步判断，缓存中的和数据库中的是否一致,一致则进行请求/否则会话已失效
        
        
//        let data = try! AES256.encrypt(Data(base64Encoded: self.id!)!, key: cipherKEY)

    }
}

struct ErrorModel: Content,ResponseResultFormatProtocol {
    typealias ResultType = [String]
    var status: Int
    var message: String
    var result: [String]?
}
func callFail(_ message: String,status: Int,req: Request) throws -> Future<Response> {
    let response = try ErrorModel(status: status, message: message, result: nil).encode(for: req)
    return response
}
